package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.qf.common.MyThreadLocal;
import com.qf.entity.*;
import com.qf.exception.CustomException;
import com.qf.mapper.OrderMapper;
import com.qf.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderDetailService orderDetailService;


    /**
     * 下单
     *
     * @param orders
     * @return
     */
    @Override
    public boolean submit(Orders orders) {
        // A. 获得当前用户id, 查询当前用户的购物车数据
        //获取当前用户id
        Long userId = MyThreadLocal.getCreateUser();

        // B. 根据当前登录用户id, 查询用户数据:购物车数据
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> cartList = shoppingCartService.list(wrapper);

        //如果该用户的购物车没有添加商品
        if (cartList == null || cartList.size() == 0) {
            throw new CustomException("购物车为空,请先添加商品");
        }

        //根据用户id查询到用户对象
        User user = userService.getById(userId);

        // C. 根据用户对象, 查询该用户地址数据:通过传过来的地址id查询到对应地址信息
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if (addressBook == null) {
            throw new CustomException("用户地址信息有误，不能下单");
        }
        //得到订单号
        long orderId = IdWorker.getId();
        AtomicInteger amount = new AtomicInteger(0);

        // D. 组装订单明细数据, 批量保存订单明细
        List<OrderDetail> orderDetails = cartList.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply
                    (new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        // E. 组装订单数据, 批量保存订单数据
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        //向订单表插入数据,
        this.save(orders);
        //向订单明细表插入数据
        orderDetailService.saveBatch(orderDetails);
        // F. 删除当前用户的购物车列表数据
        shoppingCartService.remove(wrapper);

        return true;
    }

    /**
     * 用户订单明细
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Page<Orders> userOrder(Integer page, Integer pageSize) {

        //分页工具
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        //查询条件
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Orders::getOrderTime);
        wrapper.eq(Orders::getUserId,MyThreadLocal.getCreateUser());
        Page<Orders> userPage = this.page(pageInfo, wrapper);
        return userPage;
    }

    /**
     * 后台订单明细
     * 订单明细查询
     * 分页,条件,时间
     *
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @Override
    public Page<Orders> userOrders(Integer page, Integer pageSize, String number, String beginTime, String endTime) throws ParseException {

        //转换时间格式
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        //分页工具
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        //查询条件
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        if (number != null && number != "") {
            wrapper.like(Orders::getNumber, number);
        }
        if (beginTime != null && endTime != null) {
            LocalDateTime beg = LocalDateTime.parse(beginTime, dateTimeFormatter);
            LocalDateTime end = LocalDateTime.parse(endTime, dateTimeFormatter);
            wrapper.gt(beg!=null,Orders::getOrderTime, beg);
            wrapper.lt(end!=null,Orders::getOrderTime, end);
           // wrapper.between(Orders::getOrderTime,beg,end);
        }
        //排序
        wrapper.orderByDesc(Orders::getOrderTime);
        Page<Orders> page1 = this.page(pageInfo, wrapper);
        return page1;
    }
}